package cn.git.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description: Redis序列化配置
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-09-23
 */
@Component
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    /**
     * 默认字符集
     */
    private final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    /**
     * 泛型类型
     */
    Class<T> clazz;

    /**
     * 配置全局类型支持
     */
    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    /**
     * 序列化构造函数
     *
     * @param t
     */
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    /**
     * 反序列化
     *
     * @param bytes
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || 0 >= bytes.length) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz);
    }
}
